import { Injectable, Logger } from '@nestjs/common'
import { Cron } from '@nestjs/schedule'
import { QueryRunner, Repository } from 'typeorm'
import { InjectRepository } from '@nestjs/typeorm'
import { OrderEntity } from '../entities/order.entity'

@Injectable()
export class OrderScheduleService {
  private readonly logger = new Logger(OrderScheduleService.name)
  private readonly isProd: boolean

  constructor(
    @InjectRepository(OrderEntity)
    private readonly orderRepository: Repository<OrderEntity>
  ) {
    const nodeEnv = process.env.NODE_ENV?.toLowerCase() || 'development'
    this.isProd = nodeEnv === 'production'
  }

  // 本地启动项目时自动执行一次新品过期检查（开发环境）
  async onModuleInit() {
    if (!this.isProd) {
      console.log('【开发环境】启动时执行自动完成过期订单任务...')
      await Promise.all([
        this.autoFinishMeal()
      ])
    }
  }

  // 线上定时任务：每天凌晨3点执行（仅生产环境生效）
  @Cron('0 0 3 * * *', { timeZone: 'Asia/Shanghai' })
  async handleTimeoutOrders() {
    if (this.isProd) {
      console.log('【生产环境】定时执行自动完成订单任务...')
      await Promise.all([
        this.autoFinishMeal()
      ])
    }
  }

  // 自动完成过期订单（3天未完成用餐，自动完成）
  private async autoFinishMeal() {
    const queryRunner: QueryRunner = this.orderRepository.manager.connection.createQueryRunner()
    try {
      // 开启事务：保证更新操作的原子性
      await queryRunner.connect()
      await queryRunner.startTransaction()

      const thresholdTime = Math.floor(Date.now() / 1000) - 3 * 24 * 60 * 60

      const result = await queryRunner.manager
        .createQueryBuilder()
        .update(OrderEntity)
        .set({ status: 2 })
        .where('status = 1 AND create_time <= :thresholdTime', { thresholdTime })
        .execute()

      // 提交事务
      await queryRunner.commitTransaction()
      console.log(`订单自动完成任务执行成功，共更新 ${result.affected || 0} 个订单`)
    } catch (error) {
      // 异常时回滚事务
      await queryRunner.rollbackTransaction()
      console.error('订单自动完成任务执行失败', error.stack)
    } finally {
      await queryRunner.release()
    }
  }
}
